package com.aruba.xfermodeapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 刮刮卡
 */
public class GuaguakaView extends View {
    private Bitmap bitmapRes, bitmapSrc, bitmapDst;
    private Paint mPaint = new Paint();
    private Paint pathPaint = new Paint();
    private Path path = new Path();
    //透明画布
    private Canvas dstCanvas;

    public GuaguakaView(Context context) {
        this(context, null);
    }

    public GuaguakaView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GuaguakaView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setLayerType(LAYER_TYPE_SOFTWARE,null);
        
        bitmapRes = BitmapFactory.decodeResource(getResources(), R.mipmap.guaguaka_text1);
        bitmapSrc = BitmapFactory.decodeResource(getResources(), R.mipmap.guaguaka);
        bitmapDst = Bitmap.createBitmap(bitmapSrc.getWidth(), bitmapSrc.getHeight(), Bitmap.Config.ARGB_8888);
        dstCanvas = new Canvas(bitmapDst);
        
        mPaint.setDither(true);

        pathPaint.setStyle(Paint.Style.STROKE);
        pathPaint.setStrokeWidth(50);
        pathPaint.setStrokeCap(Paint.Cap.ROUND);
        pathPaint.setColor(Color.WHITE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(event.getX(), event.getY());
                postInvalidate();
                return true;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(event.getX(), event.getY());
                postInvalidate();
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //画结果
        canvas.drawBitmap(bitmapRes, 0, 0, mPaint);

        int layerId = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        //画DST
        dstCanvas.drawPath(path,pathPaint);
        canvas.drawBitmap(bitmapDst, 0, 0, mPaint);

        Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT);
        mPaint.setXfermode(xfermode);
        canvas.drawBitmap(bitmapSrc,0,0,mPaint);
        mPaint.setXfermode(null);

        canvas.restoreToCount(layerId);
    }
}
